package com.deng.test.service.impl;

import com.deng.test.entity.User;
import com.deng.test.exception.InvalidTokenException;
import com.deng.test.mapper.UserMapper;
import com.deng.test.service.UserService;
import com.deng.test.util.JwtUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Component
public class UserServiceImpl implements UserService {
    private final UserMapper mapper;
    private final JwtUtil jwtUtil;

    public UserServiceImpl(UserMapper mapper, JwtUtil jwtUtil) {
        this.mapper = mapper;
        this.jwtUtil = jwtUtil;
    }

    public List<User> getAllUser() {
        return mapper.getAllUser();
    }

    @Override
    public User getUserByName(String name) {
        return mapper.getUserByName(name);
    }

    @Override
    public HashMap<String, Object> getToken(String email, String password) throws Exception {
        //在系统中搜索是否存在这个用户
        User user = mapper.getUser(email);
        Optional.ofNullable(user).orElseThrow(() -> new InvalidTokenException("用户不存在"));
        //密码是否一致
        if (!password.equals(user.getPassword())) {
            throw new InvalidTokenException("密码错误");
        }
        HashMap<String, Object> result = new HashMap<>();
        String token = jwtUtil.generateJwt(email);
        result.put("token", token);
        return result;
    }

    @Override
    public HashMap<String, Object> register(String username, String email, String password) {
        HashMap<String, Object> hashMap = new HashMap<>();
        User userByEmail = mapper.getUserByEmail(email);
        Optional.ofNullable(userByEmail).ifPresent(item->{throw new RuntimeException("用户已存在！");});

        User user = new User();
        user.setEmail(email);
        user.setUsername(username);
        user.setPassword(password);
        mapper.register(user);
        return hashMap;
    }
}
